package com.dalei.vds.soap;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.dalei.vdserver.shared.model.ErrorCode;
import com.dalei.vdserver.shared.soap.TimeSoap;

import android.content.Context;

public class TimeSoapImpl extends BaseSoap implements TimeSoap {

	private String url;

	private HttpTransportSE ht;

	private SoapSerializationEnvelope envelope;
	
	public TimeSoapImpl(String ipAddress, int port, int timeout) {
		// TODO Auto-generated constructor stub
		super(ipAddress, port, timeout);
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("http://");
		stringBuffer.append(super.getIpAddress());
		stringBuffer.append(":");
		stringBuffer.append(super.getPort());
		stringBuffer.append("/VDServer/TimeService?wsdl");
		url = stringBuffer.toString();
		ht = new HttpTransportSE(url, super.getTimeout());
		envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	}

	public TimeSoapImpl(Context context) {
		// TODO Auto-generated constructor stub
		super(context);
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("http://");
		stringBuffer.append(super.getIpAddress());
		stringBuffer.append(":");
		stringBuffer.append(super.getPort());
		stringBuffer.append("/VDServer/TimeService?wsdl");
		url = stringBuffer.toString();
		ht = new HttpTransportSE(url, super.getTimeout());
		envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	}

	public long getServerTime() {
		// TODO Auto-generated method stub
		SoapObject request = new SoapObject(NAMESPACE, "getServerTime");
		envelope.bodyOut = request;
		long time = 0;
		try {
			ht.call(null, envelope);
			SoapObject result = (SoapObject) envelope.bodyIn;
			String returnObeject = result.getProperty("return").toString();
			time = Long.parseLong(returnObeject);
		} catch (ClassCastException e) {
			// TODO: handle exception
			e.printStackTrace();
			return ErrorCode.INTERNAL_ERROR;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ErrorCode.INTERNAL_ERROR;
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ErrorCode.INTERNAL_ERROR;
		}
		return time;
	}

}
